<template>
  <el-form
    size="large"
    :rules="FORM_RULES"
    ref="formRef"
    :model="formData"
    label-width="100px"
  >
    <el-form-item prop="privilegeName" label="名称">
      <el-input clearable placeholder="请输入权限名称" v-model="formData.privilegeName" />
    </el-form-item>
    <el-form-item prop="directory" label="类型">
      <el-radio-group v-model="formData.directory">
        <el-radio-button v-for="item in privilegeType" :key="item" :label="item.value">
          {{item.label}}
        </el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item prop="showOrder" label="代码排序">
      <el-input-number v-model="formData.showOrder" :step="2" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item prop="remark" label="备注">
      <el-input :rows="3" clearable placeholder="请输入备注" v-model="formData.remark" type="textarea"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
      <el-button type="info" v-if="props.hideClose !== 'hide' " @click="handleClose">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { RuleBeanData, FORM_RULES } from '@/model/system/privilege/model'
import { loadPrivilegeById, saveOrUpdate, getMaxIndex } from '@/api/system/privilege/PrivilegeManager'

const formRef = ref()
const props = defineProps({ fid: String, id: String, hideClose: String })
const emit = defineEmits(['close-dialog', 'reload-data'])
const formData = ref({ ...RuleBeanData, fid: props.fid })
const privilegeType = [{ value: 0, label: '权限' }, { value: 1, label: '文件夹' }]

const handleClose = () => {
  emit('close-dialog')
}

const submitForm = async (formRef) => {
  if (!formRef) return
  formRef.validate(valid => {
    if (valid) {
      saveOrUpdate(formData.value).then(() => {
        ElMessage.success('保存成功！')
        emit('reload-data')
        if (props.hideClose !== 'hide') {
          handleClose()
        }
      }).catch(() => {
        ElMessage.error('保存失败！')
      })
    }
  })
}

watch(
  () => props.id,
  () => {
    if (props.id) {
      loadPrivilegeById(props.id).then(data => {
        formData.value = { ...data }
      })
    }
  }
)

onMounted(() => {
  if (props.id) {
    loadPrivilegeById(props.id).then(data => {
      formData.value = { ...data }
    })
  } else {
    formData.value.directory = 0
    getMaxIndex(props.fid).then(data => {
      formData.value.showOrder = data + 2
    })
  }
})
</script>
